import httpx
import time
import datetime
import hashlib
import uuid

cpid = 'wwad839aa938663a8c'  # 企业微信的企业ID
cpsecret = '7SUQzpIm6pxT1AY17NxiLjkGbIjZAg7J7kneD05HEcM'  # 企业微信自建应用的Secret
vul_like = ['weblogic', 'apache']  # 关注的组件，可添加
risk_like = ['CRITICAL', 'HIGH', 'MEDIUM']  # 关注的威胁级别，可添加
care = 1  # 0表示只接收关注组件的漏洞，1表示所有组件的高危漏洞


url = 'https://services.nvd.nist.gov/rest/json/cves/1.0'
headers = {
    'User-Agent':
        'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:56.0) Gecko/20100101 Firefox/56.0 Waterfox/56.3',
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
    'Accept-Language': 'zh,en;q=0.5',
    'Accept-Encoding': 'gzip, deflate',
    'Connection': 'close',
    'Upgrade-Insecure-Requests': '1',
}
access_token = ''
content = ''  # 表示企业微信的文本信息


def get_cve():
    # 时间比我们晚取三天前的漏洞有cvss评分
    today = datetime.date.today()
    yesterday = today - datetime.timedelta(days=3)  # 3
    pubStartDate = str(yesterday) + 'T00:00:00:000 UTC-05:00'

    if care == 1:
        for risk in risk_like:
            params = {'pubStartDate': pubStartDate, 'cvssV3Severity': risk}
            with httpx.Client(params=params) as client:
                res = client.get(url).json()
            if res['totalResults'] > 0:
                res_content(res)
    else:
        for risk in risk_like:
            for vul in vul_like:
                params = {'pubStartDate': pubStartDate, 'keyword': vul, 'cvssV3Severity': risk}
                with httpx.Client(params=params) as client:
                    res = client.get(url).json()
                if res['totalResults'] > 0:
                    res_content(res)


def res_content(res):
    global content
    message = time.strftime("%Y-%m-%d", time.localtime()) + '号共有`' + str(
        res['totalResults']) + '`个漏洞'
    send_wx(access_token, message)  # 每日提示消息

    for i in range(res['totalResults']):
        id = '漏洞编号：' + res['result']['CVE_Items'][i]['cve']['CVE_data_meta']['ID'] + '\n'
        pubdate = '公开日期：' + res['result']['CVE_Items'][i]['publishedDate'] + '\n'
        try:
            baseSeverity = '<font color="warning">漏洞等级：</font>' + \
                           res['result']['CVE_Items'][i]['impact']['baseMetricV3']['cvssV3']['baseSeverity']
            score = '<font color="warning">CVSSV3</font>：' + str(
                res['result']['CVE_Items'][i]['impact']['baseMetricV3']['cvssV3']['baseScore']) + '\n'
        finally:
            description = res['result']['CVE_Items'][i]['cve']['description']['description_data'][0]['value']
            description = translate(description)  # 翻译
            description = '漏洞描述：<font color=\"info\">' + description + '</font>\n'
            content = '**新增漏洞告警**\n' + id + pubdate + baseSeverity + ' ' + score + description
            send_wx(access_token, content)  # 发送到企业微信


def translate(translate_text):  # 翻译描述信息
    youdao_url = 'https://openapi.youdao.com/api'  # 有道api地址
    input_text = ""  # 翻译文本生成sign前进行的处理
    # 当文本长度小于等于20时，取文本
    if (len(translate_text) <= 20):
        input_text = translate_text
    # 当文本长度大于20时，进行特殊处理
    elif (len(translate_text) > 20):
        input_text = translate_text[:10] + str(len(translate_text)) + translate_text[-10:]
    time_curtime = int(time.time())  # 秒级时间戳获取
    app_id = "08b017f1529e7308"  # 应用id
    uu_id = uuid.uuid4()  # 随机生成的uuid数，为了每次都生成一个不重复的数
    app_key = "YQnrzuIDLziRP1b07PjijZGtN5ahqZzC"  # 应用密钥
    sign = hashlib.sha256((app_id + input_text + str(uu_id) + str(time_curtime) + app_key).encode('utf-8')).hexdigest()  # sign生成
    data = {
        'q': translate_text,  # 翻译文本
        'from': "en",  # 源语言
        'to': "zh-CHS",  # 翻译语言
        'appKey': app_id,  # 应用id
        'salt': uu_id,  # 随机生产的uuid码
        'sign': sign,  # 签名
        'signType': "v3",  # 签名类型，固定值
        'curtime': time_curtime,  # 秒级时间戳
    }
    res=httpx.get(youdao_url, params = data).json() # 获取返回的json()内容
    return (res["translation"][0]) # 获取翻译内容

def get_token():
    global cpid,cpsecret,access_token
    url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken"
    parms = {'corpid': cpid,'corpsecret': cpsecret}
    res = httpx.get(url,headers=headers,params=parms).json()
    errcode = res['errcode']
    if errcode != 0:
        print('something wrong:\nyou can see: https://open.work.weixin.qq.com/devtool/query?e='+ str(errcode))
    else:
        access_token = res['access_token']


def send_wx(access_token, content):
    url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token="
    data = {
        "touser": "YaoYuWei",
        "msgtype": "markdown",
        "agentid": 1000002,
        "markdown": {"content": content},
        "safe": 0,
        "enable_id_trans": 0,
        "enable_duplicate_check": 0,
        "duplicate_check_interval": 1800
    }
    res = httpx.post(url + access_token, headers=headers, json=data).json()
    errcode = res['errcode']
    if errcode != 0:
        print('something wrong:\nyou can see: https://open.work.weixin.qq.com/devtool/query?e=' + str(errcode))


def main():
    get_token()
    get_cve()


if __name__ == "__main__":
    main()
